import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
  type ActionType,
  PageContainer,
  type ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import {
  Button,
  Form,
  Input,
  InputNumber,
  Modal,
  message,
  Select,
  Tag,
  Tree,
} from 'antd';
import { useEffect, useRef, useState } from 'react';
import {
  createPermission,
  deletePermission,
  getPermissions,
  getPermissionTree,
  updatePermission,
} from '@/services/ant-design-pro/rbac';

const Permissions: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [permissionTree, setPermissionTree] = useState<API.Permission[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingPermission, setEditingPermission] =
    useState<API.Permission | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    loadPermissionTree();
  }, []);

  const loadPermissionTree = async () => {
    try {
      const response = await getPermissionTree();
      setPermissionTree(response.data || []);
    } catch (_error) {
      message.error('加载权限树失败');
    }
  };

  const handleCreate = () => {
    setEditingPermission(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: API.Permission) => {
    setEditingPermission(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个权限吗？',
      onOk: async () => {
        try {
          await deletePermission(id);
          message.success('删除成功');
          actionRef.current?.reload();
          loadPermissionTree();
        } catch (_error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingPermission?.id) {
        await updatePermission(editingPermission.id, values);
        message.success('更新成功');
      } else {
        await createPermission(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      actionRef.current?.reload();
      loadPermissionTree();
    } catch (_error) {
      message.error('操作失败');
    }
  };

  const renderPermissionTree = (permissions: API.Permission[]): any[] => {
    return permissions.map((permission) => {
      if (permission.children && permission.children.length > 0) {
        return {
          title: permission.name,
          key:
            permission.id ||
            `permission-${Math.random().toString(36).substr(2, 9)}`,
          children: renderPermissionTree(permission.children),
        };
      }
      return {
        title: permission.name,
        key:
          permission.id ||
          `permission-${Math.random().toString(36).substr(2, 9)}`,
      };
    });
  };

  const renderType = (type: any) => {
    const typeMap: Record<string, { text: string; color: string }> = {
      menu: { text: '菜单', color: 'blue' },
      button: { text: '按钮', color: 'green' },
      api: { text: 'API', color: 'orange' },
    };
    const config = typeMap[type] || { text: type, color: 'default' };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const renderStatus = (status: any) => (
    <Tag color={status === 'active' ? 'green' : 'red'}>
      {status === 'active' ? '启用' : '禁用'}
    </Tag>
  );

  const columns: ProColumns<API.Permission>[] = [
    {
      title: '权限名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '权限编码',
      dataIndex: 'code',
      key: 'code',
      width: 200,
    },
    {
      title: '权限类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: renderType,
    },
    {
      title: '资源',
      dataIndex: 'resource',
      key: 'resource',
      width: 200,
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: renderStatus,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 80,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 150,
      render: (text, record, _, action) => [
        <Button
          key="edit"
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>,
        <Button
          key="delete"
          type="link"
          size="small"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleDelete(record.id || '')}
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: '权限管理',
        breadcrumb: {
          items: [
            {
              title: '系统管理',
            },
            {
              title: '权限管理',
            },
          ],
        },
      }}
    >
      <div style={{ display: 'flex', gap: 24 }}>
        {/* 左侧权限树 */}
        <div
          style={{
            width: 400,
            background: '#fff',
            padding: 16,
            borderRadius: 8,
            minWidth: 350,
            maxWidth: 500,
          }}
        >
          <h4>权限树结构</h4>
          <Tree
            treeData={renderPermissionTree(permissionTree)}
            fieldNames={{
              title: 'name',
              key: 'id',
              children: 'children',
            }}
            style={{
              minHeight: 400,
              overflow: 'auto',
            }}
          />
        </div>

        {/* 右侧权限列表 */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <ProTable<API.Permission>
            columns={columns}
            actionRef={actionRef}
            rowKey="id"
            search={{
              labelWidth: 120,
            }}
            request={async (params: any) => {
              const response = await getPermissions({
                current: params.current,
                pageSize: params.pageSize,
              });
              return {
                data: response.data || [],
                success: response.success,
                total: response.total,
              };
            }}
            columnsState={{
              persistenceKey: 'permissions-table',
              persistenceType: 'localStorage',
            }}
            rowSelection={{}}
            tableAlertRender={false}
            toolBarRender={() => [
              <Button
                key="create"
                type="primary"
                onClick={handleCreate}
                icon={<PlusOutlined />}
              >
                新建权限
              </Button>,
            ]}
          />
        </div>
      </div>

      {/* 创建/编辑权限弹窗 */}
      <Modal
        title={editingPermission ? '编辑权限' : '新建权限'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item
            name="name"
            label="权限名称"
            rules={[{ required: true, message: '请输入权限名称' }]}
          >
            <Input placeholder="请输入权限名称" />
          </Form.Item>

          <Form.Item
            name="code"
            label="权限编码"
            rules={[{ required: true, message: '请输入权限编码' }]}
          >
            <Input placeholder="请输入权限编码" />
          </Form.Item>

          <Form.Item
            name="type"
            label="权限类型"
            rules={[{ required: true, message: '请选择权限类型' }]}
          >
            <Select placeholder="请选择权限类型">
              <Select.Option value="menu">菜单</Select.Option>
              <Select.Option value="button">按钮</Select.Option>
              <Select.Option value="api">API</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item name="resource" label="资源">
            <Input placeholder="请输入资源路径或标识" />
          </Form.Item>

          <Form.Item name="action" label="操作">
            <Input placeholder="请输入操作类型" />
          </Form.Item>

          <Form.Item name="parentId" label="父级权限">
            <Select placeholder="请选择父级权限" allowClear>
              {permissionTree.map((permission) => (
                <Select.Option key={permission.id} value={permission.id}>
                  {permission.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item name="sort" label="排序">
            <InputNumber
              placeholder="请输入排序值"
              min={0}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Select.Option value="active">启用</Select.Option>
              <Select.Option value="inactive">禁用</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item name="description" label="描述">
            <Input.TextArea rows={3} placeholder="请输入权限描述" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default Permissions;
